package com.dsteiner.widgets.server;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.dsteiner.widgets.client.ObjectUtil;
import com.dsteiner.widgets.client.StringUtil;

public class ServerUtil {

	public static <T> List<T> sort(List<T> list, final String field, final boolean isAscending) {
		Collections.sort(list, new Comparator<T>(){
			public int compare(T o1, T o2) {
				try {
					String getMethod = "get"+StringUtil.toUpperCaseFirstChar(field);
					Method method = o1.getClass().getMethod(getMethod, null);
					Comparable value1 = (Comparable) o1.getClass().getMethod(getMethod, null).invoke(o1, null);
					Comparable value2 = (Comparable) o2.getClass().getMethod(getMethod, null).invoke(o2, null);
					return isAscending ? ObjectUtil.compare(value1, value2) : ObjectUtil.compare(value2, value1);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return 0;
			}
		});
		return list;
	}

	public static <T> Set<Field> getAnnotationFields(Class<T> objectClass,
			Class annotationClass) {
		Set<Field> properties = new HashSet<Field>();
		Field[] declaredFields = objectClass.getDeclaredFields();
		for (int i = 0; i < declaredFields.length; i++) {
			Field field = declaredFields[i];
			Object annotation = field.getAnnotation(annotationClass);
			if(annotation != null)
				properties.add(field);
		}
		return properties;
	}

	public static Object getProperty(String property, Object object){
		try{
			Method getter = object.getClass().getMethod("get"+StringUtil.toUpperCaseFirstChar(property));
			Object propertyValue = getter.invoke(object);
			return propertyValue;
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}

    /**
     * Scans all classes accessible from the context class loader which belong to the given package and subpackages.
     *
     * @param packageName The base package
     * @return The classes
     * @throws ClassNotFoundException
     * @throws IOException
     */
    public static List<Class> getClasses(String packageName) {
    	try{
	        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
	        assert classLoader != null;
	        String path = packageName.replace('.', '/');
	        Enumeration<URL> resources = classLoader.getResources(path);
	        List<File> dirs = new ArrayList<File>();
	        while (resources.hasMoreElements()) {
	            URL resource = resources.nextElement();
	            dirs.add(new File(resource.getFile()));
	        }
	        ArrayList<Class> classes = new ArrayList<Class>();
	        for (File directory : dirs) {
	            classes.addAll(findClasses(directory, packageName));
	        }
	        return classes;
    	}catch(Exception ex){
    		ex.printStackTrace();
    	}
    	return null;
    }

    /**
     * Recursive method used to find all classes in a given directory and subdirs.
     *
     * @param directory   The base directory
     * @param packageName The package name for classes found inside the base directory
     * @return The classes
     * @throws ClassNotFoundException
     */
    private static List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException {
        List<Class> classes = new ArrayList<Class>();
        if (!directory.exists()) {
            return classes;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file, packageName + "." + file.getName()));
            } else if (file.getName().endsWith(".class")) {
                classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
            }
        }
        return classes;
    }

}
